package com.yuzi.model.systemMo;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.yuzi.model.BaseMo.BaseModel;

import java.util.List;

public class SysDict extends BaseModel<SysDict> {

    public Page<Record> findAllSysDict(int pageNumber, int pageSize,String dictNameSele,String dictSele){
        String sql = "SELECT sd.*,sd1.subNode ";
        StringBuffer selectExcept=new StringBuffer("FROM sys_dict sd  ");
        selectExcept.append("LEFT JOIN ( ");
        selectExcept.append(" SELECT pcode ,GROUP_CONCAT(CODE,' (',NAME,')  ') subNode ");
        selectExcept.append(" FROM sys_dict WHERE pcode != '0' GROUP BY pcode ");
        selectExcept.append(" ) sd1 ON sd.code = sd1.pcode ");
        selectExcept.append(" WHERE sd.pcode = '0' ");
        if(dictNameSele!=null && !dictNameSele.equals(""))
            selectExcept.append(" AND name like CONCAT('%','"+dictNameSele+"','%') ");
        if(dictSele!=null && !dictSele.equals(""))
            selectExcept.append(" AND CODE LIKE CONCAT('%','"+dictSele+"','%') ");
        selectExcept.append(" order by sd.id ");

        return Db.paginate(pageNumber,pageSize,false,sql,selectExcept.toString());
    }


    public int deleteSysDictByPcode(String pcode){
        String sql = "delete from sys_dict where pcode = ?";
        return Db.update(sql,pcode);
    }

    public List<SysDict> findSysDictByPcode(String pcode){
        String sql = "select * from sys_dict where pcode = ? order by id";
        return this.find(sql,pcode);
    }



    public SysDict findAllSysDictById(Integer id){
        String sql = "select * from sys_dict where id = ? ";
        return this.findById(id);
    }


    public int addSysDict(SysDict sysDict){
        int maxIndex = getMaxIndex(this);
        boolean isSuc = sysDict.set("id",maxIndex+1).save();
        if (isSuc)
            return sysDict.getInt("id");
        else
            return 0;
    }

    //修改父集或子集
    public boolean editSysDict(SysDict sysDict){
        return sysDict.update();
    }

    public boolean isExistCode(SysDict sysDict) {
        String sql = "select count(0) from sys_dict where code = ? and pcode=? ";
        if(sysDict.getInt("id") != null){
            sql += " and id <> ? ";
        }else {
            sql += " and null is ?"; //此处为解决下面传递3个参数的问题
        }
        Long count = Db.queryLong(sql,sysDict.get("code"),sysDict.get("pcode"),sysDict.getInt("id"));
        return count>0 ? true:false;
    }
}
